package com.example.rdcproject.ving.notes.service;

import com.example.rdcproject.ving.notes.util.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OperateBlack {

    private List<String> blackList = new ArrayList<>();

    private Connection connection;
    private PreparedStatement statement;
    ConnectionPool connectionPool = null;
    // 添加用户到黑名单
    public boolean addBlacklist(String nickname) throws SQLException {
        try {

            connectionPool = ConnectionPool.getInstance();
            connection = connectionPool.getConnection();

            //定义SQL查询语句
            String sql = "UPDATE user set user_isBlack=? where user_nickname= ?";
            statement = connection.prepareStatement(sql);
            statement.setBoolean(1, true);
            statement.setString(2, nickname);

           statement.executeUpdate();

        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            connectionPool.releaseConnection(connection);
            DBUtils.close(statement);
        }

        if (blackList.contains(nickname)) {
            return false;
        }
        blackList.add(nickname);
        return true;
    }

    // 从黑名单中移除用户
    public boolean removeBlacklist(String nickname) {
        if (!blackList.contains(nickname)) {
            return false;
        }
        blackList.remove(nickname);
        return true;
    }

    // 判断用户是否被拉黑
    public boolean isBlacklist(String nickname) {
        return blackList.contains(nickname);
    }

    //更新黑名单
    public void update() throws Exception {

        try {
            connectionPool = ConnectionPool.getInstance();
            connection = connectionPool.getConnection();

            //开启事务
            connection.setAutoCommit(false);

            //定义sql语句
            String sql = "drop table BlackList if exists ";
            statement.execute(sql);
            String sql2 = "create table BlackList if not exists ";
            statement.execute(sql2);

            //批量添加数据
            String sql3 = "insert into BlackList (nickname) values ?";
            statement=connection.prepareStatement(sql3);

            for (String s : blackList) {
                statement.setString(1,s);
                statement.addBatch();
            }

           statement.executeBatch();
            //提交事务
           connection.commit();
            System.out.println("更新成功");
        }catch (Exception e){
            e.printStackTrace();
            connection.rollback();
        }finally {
            connectionPool.releaseConnection(connection);
            DBUtils.close(statement);
        }
        }



}
